#include "selfwiki.h"

#include <config/config.h>

#include <QWebEngineProfile>
#include <QWebEngineScript>
#include <QWebEngineScriptCollection>
#include <QWebEngineView>
#include <qd.h>

#include <QFileInfo>
#include <QWebEngineSettings>
#include <response.h>

SelfWiki::SelfWiki() : plugin_default(QWebEngineSettings::defaultSettings()->testAttribute(QWebEngineSettings::PluginsEnabled))
{
    m_interactive = 0;
}

QString SelfWiki::name()
{
    return "数据集自定义 - 链接源";
}

QList<QListWidgetItem *> SelfWiki::searching_item(const QString &text)
{
    QList<QListWidgetItem *> lists;
    if (m_interactive == 0) {
        auto list = Response(0, Config::getAppDataConfig()).toList();
        for (int row = 0; row < list.count(); ++row) {
            QVariantMap map = list.at(row).toMap();

            auto title = map.value("title").toString();
            if (text.isEmpty() || title.contains(text, Qt::CaseInsensitive)) {
                auto item = new QListWidgetItem;
                item->setText(map.value("title").toString());
                item->setData(990, map.value("prefix").toString());
                item->setData(991, map.value("content").toString());
                lists << item;
            }
        }
    }

    if (m_interactive == 1) {
        auto title = m_map.value("title").toString();
        auto prefix = m_map.value("prefix").toString();
        auto content = m_map.value("content").toString();

        auto rows = content.split("\n", Qt::SkipEmptyParts);
        for (int row = 0; row < rows.count(); ++row) {
            auto line = rows.at(row);

            auto title = line.mid(line.indexOf(">")+1);
            title = title.mid(0, title.indexOf("</a>"));
            auto href = line.mid(line.indexOf("href=\"")+6);
            href = href.mid(0, href.indexOf("\">"));

            if (text == m_key || text.isEmpty() || title.contains(text, Qt::CaseInsensitive)) {
                auto item = new QListWidgetItem;
                item->setText(title);
                item->setData(990, prefix);
                item->setData(991, href);
                lists << item;
            }
        }
    }

    return lists;
}

QString SelfWiki::content_item(const QListWidgetItem *item)
{
    return item->data(990).toString() + item->data(991).toString();
}

/**
 * @brief SelfWiki::interactive
 * @param text
 * @return 触发交互式检查
 */
bool SelfWiki::interactive(const QString &text)
{
    if (m_interactive == 0) {

        m_key = text;

        auto list = Response(0, Config::getAppDataConfig()).toList();
        for (int row = 0; row < list.count(); ++row) {
            QVariantMap map = list.at(row).toMap();
            auto title = map.value("title").toString();
            if (title == m_key) {
                m_map = map;
                break;
            }
        }

        return m_interactive++ < 1;
    }

    return false;
}

/**
 * @brief SelfWiki::interactive_running
 * @return 当前是否为交互模式
 */
bool SelfWiki::interactive_running()
{
    return m_interactive > 0;
}

void SelfWiki::interactive_restore()
{
    m_interactive = 0;
}

Wiki::ContentMode SelfWiki::contentMode()
{
    // FIXME: 之所以使用 NoContent 可能是因为 load 时为空时，可能
    // 也许需要在外部处理其它分类操作在默认 URL 时的可能的异常
    // return m_map.value("javascript").toString().isEmpty() ? Url : NoContent;
    return NoContent;
}

void SelfWiki::content_item(const QListWidgetItem *item, QWebEngineView *view)
{
    QString code(m_map.value("javascript").toString());

    QWebEngineProfile *profile = view->page()->profile();
    profile->scripts()->clear();

    // is file:// OK?
    auto prefix = item->data(990).toString();
    if (prefix.startsWith("file://")) {
        QUrl url(item->data(990).toString() + item->data(991).toString());
        QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::PluginsEnabled, true);

        qd << url.toString();
        view->setUrl(url);
        return;
    }

    // is file Ok?
    QFileInfo file(item->data(990).toString() + item->data(991).toString());
    if (file.exists()) {
        QUrl url = QUrl::fromLocalFile(file.filePath()).toString();
        QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::PluginsEnabled, true);

        qd << file.filePath();
        qd << url.toString();
        view->setUrl(url);
        return;
    }

    QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::PluginsEnabled, plugin_default);

    view->load(item->data(990).toString() + item->data(991).toString());

    QWebEngineScript self;
    self.setSourceCode(code);
    profile->scripts()->insert(self);

    m_interceptor.setBlockUrls(m_map.value("blockurls").toString());
    view->page()->profile()->setRequestInterceptor(&m_interceptor);
}

void SelfWikiInterceptor::interceptRequest(QWebEngineUrlRequestInfo &info)
{
    auto reqeust = info.requestUrl().toString();
    auto blocked = false;
    foreach (auto var, m_blockUrls) {
        if (reqeust.contains(var, Qt::CaseInsensitive)) {
            qd << "拦截请求:" << reqeust;
            blocked = true;
            break;
        }
    }
    info.block(blocked);
    if (!blocked) {
        qd << "允许请求:" << reqeust;
    }
}

QStringList SelfWikiInterceptor::blockUrls() const
{
    return m_blockUrls;
}

void SelfWikiInterceptor::setBlockUrls(const QStringList &newBlockUrls)
{
    m_blockUrls = newBlockUrls;
}

void SelfWikiInterceptor::setBlockUrls(const QString &newBlockUrls)
{
    setBlockUrls(newBlockUrls.split("\n", Qt::SkipEmptyParts));
}
